﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.IO.Compression;
using System.Diagnostics;

namespace Kaixin.Tools
{
    public class Network
    {
        #region Member
        private string _UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.10) Gecko/2009042316 Firefox/3.0.10 (.NET CLR 3.5.30729)";
        private string _Cookie = "";
        #endregion


        /// <summary>
        /// Doing login:
        /// The page will redirect to another page while the cookie length 
        /// is too long for a string to save, so
        /// 1. post data to get cookie
        /// 2. save cookie
        /// 3. check cookie, give response
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public string PostData(string url, byte[] data)
        {
            HttpWebRequest loHttp = null;
            HttpWebResponse loWebResponse = null;
            StreamReader loResponseStream = null;
            string response = "";

            try
            {
                loHttp = (HttpWebRequest)WebRequest.Create(url);
                loHttp.AllowWriteStreamBuffering = true;
                loHttp.AllowAutoRedirect = false;
                loHttp.Method = "POST";
                loHttp.UserAgent = _UserAgent;
                loHttp.KeepAlive = true;
                loHttp.Referer = Consts.RootURL + "/";
                loHttp.ContentType = "application/x-www-form-urlencoded";
                loHttp.Headers.Add("Accept-Encoding", "gzip,deflate");

                if (_Cookie != null && !_Cookie.Equals(""))
                    loHttp.Headers.Add("Cookie", _Cookie);

                if (data != null)
                {
                    loHttp.ContentLength = data.Length;
                    Stream loPostData = loHttp.GetRequestStream();
                    loPostData.Write(data, 0, data.Length);
                    loPostData.Close();
                }

                loWebResponse = (HttpWebResponse)loHttp.GetResponse();

                // Get the cookie first
                string cookie = loWebResponse.Headers.Get("Set-Cookie");

                // Check cookie and save
                if (cookie != null && !cookie.Equals(""))
                {
                    if (cookie.IndexOf(Consts.LoginErrorCookie) < 0)
                        _Cookie = cookie;
                }

                Stream stream = loWebResponse.GetResponseStream();
                GZipStream zstream = new GZipStream(stream, CompressionMode.Decompress);
                loResponseStream = new StreamReader(zstream, Encoding.UTF8);
                //loResponseStream = new StreamReader(stream, Encoding.UTF8);
                response = loResponseStream.ReadToEnd();

                return response;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.StackTrace);
                return response;
            }
            finally
            {
                if (loWebResponse != null)
                    loWebResponse.Close();
            }

        }


        public string CallUrl(string url)
        {
            HttpWebRequest loHttp = null;
            HttpWebResponse loWebResponse = null;
            StreamReader loResponseStream = null;
            string response = "";

            try
            {
                loHttp = (HttpWebRequest)WebRequest.Create(url);
                loHttp.Method = "GET";
                loHttp.UserAgent = _UserAgent;
                loHttp.KeepAlive = true;
                loHttp.Headers.Add("Accept-Encoding", "gzip,deflate");

                if (_Cookie != null && !_Cookie.Equals(""))
                    loHttp.Headers.Add("Cookie", _Cookie);


                loWebResponse = (HttpWebResponse)loHttp.GetResponse();

                string cookie = loWebResponse.Headers.Get("Set-Cookie");
                if (cookie != null && !cookie.Equals("") && cookie.IndexOf(Consts.CookieAvailable)>=0)
                    _Cookie = cookie;

                Stream stream = loWebResponse.GetResponseStream();
                GZipStream zstream = new GZipStream(stream, CompressionMode.Decompress);
                loResponseStream = new StreamReader(zstream, Encoding.UTF8);
                //loResponseStream = new StreamReader(stream, Encoding.UTF8);
                response = loResponseStream.ReadToEnd();

                return response;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.StackTrace);
                return "";
            }
            finally
            {
                if (loWebResponse != null)
                    loWebResponse.Close();
                if (loResponseStream != null)
                    loResponseStream.Close();
            }
        }


        public byte[] GetData(string url)
        {
            HttpWebRequest loHttp = null;
            HttpWebResponse loWebResponse = null;

            try
            {
                loHttp = (HttpWebRequest)WebRequest.Create(url);
                loHttp.Method = "GET";
                loHttp.UserAgent = _UserAgent;
                loHttp.KeepAlive = true;
                loHttp.Headers.Add("Accept-Encoding", "gzip,deflate");


                if (_Cookie != null && !_Cookie.Equals(""))
                    loHttp.Headers.Add("Cookie", _Cookie);

                loWebResponse = (HttpWebResponse)loHttp.GetResponse();
                Stream stream = loWebResponse.GetResponseStream();
                GZipStream zstream = new GZipStream(stream, CompressionMode.Decompress);

                List<byte> data = new List<byte>();

                if (zstream != null)
                {
                    int b = zstream.ReadByte();
                    while (b != -1)
                    {
                        data.Add((byte)b);
                        b = zstream.ReadByte();
                    }
                }

                return data.ToArray();
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.StackTrace);
                return null;
            }
            finally
            {
                if (loWebResponse != null)
                    loWebResponse.Close();
            }

        }
       

    }
}
